/**
 * ext extension of store config;

 * store预读取类
 * @author    Zheng Kejun
 * @copyright (c) 2013, 
 * @version   0.1
 * @date      <ul>
 * <li>2013-07-31</li>
 * <li>2013-08-01</li>
 * </ul>
 *
 */

var StoreHelper = function(){
	this.handlers = new HashMap();
	this.storeMap = new HashMap();
	this.initHandles();
};	
/**
 * init cache the store handles
 */
StoreHelper.prototype.initHandles=function(){
	this.setHandle("enums",this.getEnums);
	this.setHandle("nodeById",this.getNodeById);
	this.setHandle("nodeByCode",this.getNodeByCode);
	this.setHandle("modelFields",this.getModelFields);
	this.setHandle("attrsByMid",this.attrsByMid);
};

/*
 * reset the store data[]
 */
StoreHelper.prototype.replace = function(source, target){
	var sStore = source;
	var tStore = target;
	if(typeof(source)=='string'){
		sStore = this.get(source);
	}
	if(typeof(target)=='string'){
		tStore = this.get(target);
	}	
	tStore.removeAll();
	tStore.add(sStore.getRange());	
};


StoreHelper.prototype.getNodeById=function(key){
	var nid = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : ['SID','RANK','CODE','NAME','TEXT'],
    		root : 'list', totalProperty : 'size', idProperty:'SID'
		})
	});	
	var uri = "module/Query-getNodeById.action?nid="+nid;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};

StoreHelper.prototype.getNodeByCode=function(key){
	var code = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : ['SID','RANK','CODE','NAME','TEXT'],
    		root : 'list', totalProperty : 'size', idProperty:'SID'
		})
	});	
	var uri = "module/Query-getNodeByCode.action?n="+code;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};

StoreHelper.prototype.getNodesByRank=function(key){
	var rank = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : [{name:'SID'},{name:'CODE'},{name:'NAME'},{name:'TEXT'}],
    		root : 'list', totalProperty : 'size', idProperty:'SID'
		})
	});	
	var uri = "module/Query-getNodesByRank.action?dataTO.code="+rank;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};

StoreHelper.prototype.getEnumByUrl=function(url,valueField,displayField){
	var store = new Ext.data.Store({
		fields: [
		            valueField||'CODE',
		            displayField||'TEXT'
		        ],
		autoLoad:true,
		url:url
	});	
	return store;
};


StoreHelper.prototype.getEnumsById=function(key){
	var id = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : [{name:'CODE'},{name:'NAME'},{name:'TEXT'}],
    		root : 'list', totalProperty : 'size', idProperty:'CODE'
		})
	});	
	var uri = "./meta/getEnumListById?id="+id;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};

StoreHelper.prototype.getEnumsByCode=function(key){
	var code = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : [{name:'CODE'},{name:'NAME'},{name:'TEXT'}],
    		root : 'list', totalProperty : 'size', idProperty:'CODE'
		})
	});	
	if(!code)return;
	var uri = "./meta/getEnumListByName?name="+code;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};

StoreHelper.prototype.getEnums=function(key){
	var store = this.storeMap.get(key);	
	if(!store ){
		var code = key.substr(key.indexOf('$')+1);
		var t1 = /^(0|[1-9][0-9]*)$/.test(code);
		if(t1){//rank id
			store = this.getEnumsById(key);
		}else{//enum code;
			store = this.getEnumsByCode(key);
		}
		this.storeMap.put(key,store);
	}
	return store;
};


StoreHelper.prototype.getModelFields=function(key){
	var kid = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields : ['SID','NAME','TEXT','TYPE','CODE','SIZE'],
    		root : 'list', totalProperty : 'size', idProperty:'SID'
		})
	});	
	var uri = "module/Query-getModelFields.action?mid="+kid;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	return store;
};


/**
 * init cache the enums from db
 */
StoreHelper.prototype.initEnums=function(){
	var cb = function(recs){
		  for(var i=0;i<recs.length;i++){
			var rec = recs[i];
			if(i==0)alert(objectToString(rec));
			var myStore = this.storeMap.get('enums$'+rec.get('RANK'));
			if(!myStore){
				alert(rec.get('RANK'))
				myStore = new Ext.data.ArrayStore({fields:['SID','RANK','CODE','NAME','TEXT'],idIndex:0});
				this.storeMap.put('enums$'+rec.get('RANK'),myStore);
			}
			myStore.add([rec]);
		  }	
	};
	var enumStore = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : [{name:'SID'},{name:'RANK'},{name:'CODE'},{name:'NAME'},{name:'TEXT'}],
    		root : 'list', totalProperty : 'size', idProperty:'SID'
		}),
    	url: '../module/Query-getEnumsAll.action'
    });	
	enumStore.load({callback:cb,scope:this});	
};

/**
 * set a cache handler
 * @param key
 * @param fn
 */
StoreHelper.prototype.setHandle=function(key,fn){
	this.handlers.put(key,fn);
};
/**
 * get a cache handle
 * @param key
 * @returns
 */
StoreHelper.prototype.getHandle=function(key){
	var fnKey = key;
	var func = this.handlers.get(fnKey);
	while((!func)&& fnKey.indexOf('$')>0 ){
		fnKey = fnKey.substring(0,fnKey.lastIndexOf('$'));
		func = this.handlers.get(fnKey);
	}
	if(typeof(func)=='function'){
		return func;
	}else{
		alert("no func defined for "+key);
		return function(){};//ensure no exception;
	}
};
/**
 * clone a cached store for modify
 * @param type
 * @param name
 * @returns {Ext.data.Store}
 */
StoreHelper.prototype.clone=function(type,name){
	var oStore = this.get(type,name);
	var nStore = new Ext.data.Store({
			//proxy: new Ext.data.MemoryProxy(oStore.data),
			reader: new Ext.data.ArrayReader({}, oStore.fields.items)
		});
	//nStore.loadData(oStore.data);
	nStore.add(oStore.getRange());
	return nStore;
};

/**
 * get a chached store with key
 * @param type
 * @param name
 * @returns
 */
StoreHelper.prototype.get=function(type,name){
	var key = type + (name?('$'+name):'');
	var store = this.storeMap.get(key);	
	if( store ){
		return store; 
	}else{
		var store = this.getHandle(key).call(this,key);
		this.storeMap.put(key,store);
	}
	return store;
};

/**
 * get a cached store row value
 * @param typeName
 * @param idValue
 * @returns
 */
StoreHelper.prototype.getValue=function(typeName,idValue){
	return this.get(typeName).getById(idValue).get('CODE');
};

/**
 * zerotime render
 * @returns {String}
 */
StoreHelper.prototype.getZeroTime = function(){  //获取当天零时时间
	  var today = new Date();        
	  var day   = today.getDate();                   
	  var month = today.getMonth() + 1;    
	  var year  = today.getFullYear();    
	  month     = month<10?"0"+month:month;       //数字<10，实际显示为，如5，要改成05    
	  day       = day<10?"0"+day:day;             //和月份显示一样    
	  var currentdate  = year + "-" + month + "-" + day+" 00:00:00"; //结果:2008-05-08 00:00:00,2008-12-29  
	  return(currentdate);
};

//get attrs by onwer id
StoreHelper.prototype.attrsByMid=function(key){
	var oid = key.substr(key.indexOf('$')+1); 
	var store = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
    		fields    : [{name: 'SID'},{name: 'RANK'},{name: 'NAME'},{name: 'CODE'}],
    		root : 'data', totalProperty : 'size', idProperty:'SID'
		}) 
	});	
	
	//store.load();
	///* 同步加载  nid=100021103
	var uri = "/meta-getAttrs/"+oid;
	var responseObj = doHttpPost(getContextBase()+uri);
 	var jsonObj	= Ext.decode(responseObj.text);
	store.loadData(jsonObj);
	//*/
	return store;
};


/**
 * keep the class run as singleton
 * @returns
 */
StoreHelper.getInstance=function(){
	var p=window;
	var ins;
	while((p!=p.top) && p.parent){
		p=p.parent;
		if(p.storeHelper){ins=p.storeHelper;}
	}
	//alert(ins?"reuse":"create");
	//alert(this==storeHelper);
	return ins?ins:new StoreHelper();
};

var storeHelper=StoreHelper.getInstance();



